package com.fr.plugin.control;

import com.fr.general.ComparatorUtils;
import com.fr.general.GeneralUtils;
import com.fr.json.JSONArray;
import com.fr.main.impl.WorkBook;
import com.fr.main.workbook.ResultWorkBook;
import com.fr.report.core.sheet.SheetSequenceExecutor;
import com.fr.stable.WriteActor;
import com.fr.stable.web.Repository;
import com.fr.web.RepositoryHelper;
import com.fr.web.core.ReportSession;
import com.fr.web.RTypeService;

import java.util.Map;

/**
 * @author richie
 * @date 2015-03-21
 * @since 8.0
 */
public class SheetControlActor extends WriteActor {

    private static final String SHEET_INDEX_NOT_BE_SHOW_PARA_NAME = "SHEETNOTSHOW";

    public ResultWorkBook executeWorkBook(WorkBook workBook, Map parameterMap) {
        if (parameterMap.containsKey(SHEET_INDEX_NOT_BE_SHOW_PARA_NAME)) {
            Number index = GeneralUtils.objectToNumber(parameterMap.get(SHEET_INDEX_NOT_BE_SHOW_PARA_NAME), true);
            if (index != null) {
                workBook.removeReport(index.intValue());
            } else {
                workBook.removeReport(GeneralUtils.objectToString(parameterMap.get(SHEET_INDEX_NOT_BE_SHOW_PARA_NAME)));
            }
        }
        return new SheetSequenceExecutor(workBook, parameterMap).execute(this);
    }

    public JSONArray processMultipleSheet(Repository repository) {
        Map map = repository.getReportParameterMap();
        int sheetIndex = -1;
        String sheetName = null;
        if (map.containsKey(SHEET_INDEX_NOT_BE_SHOW_PARA_NAME)) {
            Number index = GeneralUtils.objectToNumber(map.get(SHEET_INDEX_NOT_BE_SHOW_PARA_NAME), true);
            if (index != null) {
                sheetIndex = index.intValue();
            } else {
                sheetName = GeneralUtils.objectToString(map.get(SHEET_INDEX_NOT_BE_SHOW_PARA_NAME));
            }
        }
        JSONArray ja = new JSONArray();
        int reportCount = getReportCountInRepo(repository);
        for (int i = 0; i < reportCount; i++) {
            ReportSession sessionIDInfo = (ReportSession) RepositoryHelper.getSessionIDInfor(repository);
            String title = sessionIDInfo.getReportName(i);
            if (i == sheetIndex || ComparatorUtils.equals(sheetName, title)) {
                continue;
            }
            RTypeService.executeSheetName(repository, title, ja, i);
        }
        return ja;
    }


}
